package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/userAddServlet")
public class UserAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");

        //获取请求参数
        Map<String, String[]> map = request.getParameterMap();

        //使用BeanUtils 将map集合封装到User对象中
        User user = new User();
        try {
            BeanUtils.populate(user,map);

            //调用service查询
            UserServiceImpl service = new UserServiceImpl();
            service.save(user);

            //重定向到查询servlet
            response.sendRedirect(request.getContextPath()+"/userListServlet");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
